import csv
import random
import time
import pymysql


def getCsvData(csv_file):
    with open(file=csv_file, mode='r', encoding='utf-8-sig') as file:
        reader = csv.reader(file)
        list1 = []
        for index, row in enumerate(reader, 1):
            list1.append(row)
    return list1


def writeCsv(csv_file,val):
    with open(file=csv_file, mode='a', encoding='utf-8-sig') as file:
        file.write(f'\n{val}')


def getTime():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


class Logs:
    def __init__(self, path):
        self.path = path

    def info(self, val):
        with open(self.path, mode='a', encoding='utf-8') as file:
            file.write(f'\n{getTime()} [ info ] {val} ')

    def debug(self, val):
        with open(self.path, mode='a', encoding='utf-8') as file:
            file.write(f'\n{getTime()} [ debug ] {val} ')

    def err(self, val):
        with open(self.path, mode='a', encoding='utf-8') as file:
            file.write(f'\n{getTime()} [ err ] {val} ')


def getPhone(a=0):
    for i in range(0, 9):
        a = a * 10 + random.randint(1, 9)

    def ran():
        phone = random.randint(13, 18) * 10 ** 9 + a
        return phone
    return ran()


class DBhelper:
    def __init__(self, **args):
        self.log = Logs('E:/py_project/likeshop-enca/logs/logs.log')
        self.log.debug(args)
        self.dbConn = args

    def connect(self):
        try:
            self.conn = pymysql.connect(**self.dbConn, charset='utf8')
            self.cursor = self.conn.cursor()
        except Exception as result:
            print(result)
            self.log.err(f'数据库连接异常\n异常原因: {result}')
        finally:
            self.log.info(f"数据库连接成功\n数据:{self.dbConn}")

    def close(self):
        self.cursor.close()
        self.conn.close()

    def queryAll(self, sql, params=[]):
        data = None
        try:
            self.connect()
            self.cursor.execute(sql, params)
        except Exception as result:
            self.log.err(f'sql语句执行错误\nsql语句: {sql}\n参数:{params}\n错误信息:{result}')
        else:
            data = self.cursor.fetchall()
            self.log.info(f'sql执行成功\nsql语句：{sql}\n参数：{params}\n查询结果：{data}')
        finally:
            self.close()
            return data

    def queryOne(self, sql, params=[]):
        data = None
        try:
            self.connect()
            self.cursor.execute(sql, params)
        except Exception as result:
            self.log.err(f'sql语句执行错误\nsql语句：{sql}\n参数：{params}\n错误信息：{result}')
        else:
            data = self.cursor.fetchone()
            self.log.info(f'sql执行成功\nsql语句：{sql}\n参数：{params}\n查询结果：{data}')
        finally:
            self.close()
            return data

    def update(self, sql, params=[]):
        count = 0
        try:
            self.connect()
            count = self.cursor.execute(sql, params)
        except Exception as result:
            self.conn.rollback()
            self.log.err(f'sql语句执行错误\nsql语句：{sql}\n参数：{params}\n错误信息：{result}')
        else:
            self.conn.commit()
            self.log.info(f'sql执行成功\nsql语句：{sql}\n参数：{params}')
        finally:
            self.close()
            return count
